package start;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

public class DBhandler {
	//
	private Connection conn;
	private Statement st;
	private static final String database = "jdbc:mysql://127.0.0.1:3306/information_system";
	private static final String driver = "com.mysql.jdbc.Driver";
	private static final String DBusername = "root";
	private static final String DBpassword = "Braude";
	
	// c'tor
	public DBhandler() throws Exception {
		try {
			Class.forName(driver).newInstance();
		}
		catch (Exception ex) {
			throw new Exception("Couldn't load MySQL driver: "+ex.getMessage());
		}	
		
		try {
			conn = DriverManager.getConnection(database,DBusername,DBpassword);
			st = conn.createStatement();
		}
		catch (SQLException ex) {
			throw new Exception ("Coudn't connect to database: "+ ex.getMessage());
		}
	}  // end of c'tor
	
	// handle select query
	public Object selectQuery (String query){
		
		boolean isResultEmpty=true;  // for indicating if the query returned no results
		ResultSet rs=null;
		
		try {
		
			rs = st.executeQuery(query);
			
			ResultSetMetaData rsmd = rs.getMetaData();
			int numOfCols = rsmd.getColumnCount();
			
			Vector<String[]> result = new Vector<String[]>();
			
			String[] headlines=new String[numOfCols];
			for (int j=1; j<=numOfCols; j++)
				headlines[j-1] = rsmd.getColumnName(j);
			result.addElement(headlines);
			
			while (rs.next()){
				String[] tuple=new String[numOfCols];
				for (int i=1 ; i<=numOfCols ; i++)
					tuple[i-1] = rs.getString(i);
				result.addElement(tuple);
				isResultEmpty=false;  // indicating at least one tuple in the result
			}
			
			if (isResultEmpty)
				return isResultEmpty;
			else
				return result;
		
		}
		
		catch (SQLException ex){
			return ex;
		}
		
	}  // end of selectQuery
	
	public Object updateDBQuery (String query){
		
		try {
			st.executeUpdate(query);
			st.close();
			return true;
		}
		
		catch (SQLException ex){
			return ex;
		}
		
	} // end of updateDBQuery
	
	
	public void login_method(String a,String b)
	{
		
	}
	
	
	
	
}

